<template>
    <div class="app-container">
        <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
            <el-form-item label="患者名称" prop="patientName">
                <el-input v-model="queryParams.patientName" placeholder="请输入内容" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="手机号码" prop="tel">
                <el-input v-model="queryParams.tel" placeholder="请输入内容" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="患者身份证" prop="identityCard">
                <el-input v-model="queryParams.identityCard" placeholder="请输入内容" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="门店名称" prop="placePointName">
                <el-input v-model="queryParams.placePointName" placeholder="请输入内容" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="药品ID" prop="medicineId">
                <el-input v-model="queryParams.medicineId" placeholder="请输入内容" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="药品名称" prop="medicineName">
                <el-input v-model="queryParams.medicineName" placeholder="请输入内容" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" class="add" @click="handleQuery">查询</el-button>
                <el-button icon="el-icon-refresh" class="delBtn" @click="resetQuery">重置</el-button>
                <el-button icon="el-icon-download" class="delBtn" @click="bindExport">批量下载</el-button>
                <el-button icon="el-icon-search" type="primary" size="small" @click="isShow=true">批量查询</el-button>
            </el-form-item>
        </el-form>
        <!-- <el-row :gutter="10" class="mb8">
            <div class="flex_box">
                <el-upload v-hasPermi="['bus:illPatient:importData']" class="upload-demo" :action="uploadUrl"
                    :before-upload="handleBeforeUpload" :on-success="handleUploadSuccess" :headers="headers" :limit="1"
                    :show-file-list="false">
                    <el-button type="primary" plain icon="el-icon-upload2" class="add">导入</el-button>
                </el-upload>
                <el-button v-hasPermi="['bus:illPatient:importTemplate']" type="primary" plain icon="el-icon-download"
                    class="delBtn" @click="downloadTemplate">导入模板下载</el-button>
                <el-button v-hasPermi="['bus:illPatient:export']" type="warning" plain icon="el-icon-download"
                    @click="handleExport">导出</el-button>
            </div>
            <right-toolbar :show-search.sync="showSearch" @queryTable="getListData" />
        </el-row> -->
        <el-table ref="table" @selection-change="handleSelectionChange" :key="tableKey" v-loading="loading"
            :data="roleList" style="margin-top: 20px">

            <el-table-column :selectable="selectable" type="selection" width="50" />

            <el-table-column label="ID" prop="id" width="50" />
            <el-table-column label="患者名称" prop="name" />
            <el-table-column label="患者手机" prop="tel" />
            <el-table-column label="患者身份证" prop="identityCard" />
            <el-table-column label="门店名称" prop="placePointName" />
            <el-table-column label="药品ID" prop="medicineId" />
            <el-table-column label="药品" prop="medicineName" />
            <el-table-column label="提交次数" prop="batchNum" />
            <el-table-column label="更新时间" prop="updateTime" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button type="text" class="btnText" @click="handleUpdate(scope.row)">编辑</el-button>
                    <el-button type="text" class="btnText" @click="handleDwon(scope.row)">下载全部图片</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getListData" />

        <!-- 弹窗 -->
        <el-dialog title="批量查询" custom-class="dialogSty" :visible.sync="isShow" width="700px">
            <div>
                <div class="btnBox">
                    <el-upload v-hasPermi="['bus:illPatient:importData']" class="upload-demo" :action="uploadBatchQuery"
                        accept=".xlsx, .xls" :before-upload="handleBeforeUpload" :on-success="handleUploadSuccess"
                        :headers="headers" :limit="1" :show-file-list="true">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传xlsx文件</div>
                    </el-upload>
                    <el-button style="margin-left: 15px;" type="primary" size="small"
                        v-hasPermi="['bus:illPatient:export']" @click="downloadTemp">下载模板</el-button>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" class="btn" @click="isShow = false">取消</el-button>
                <el-button size="small" class="btn qd-btn" type="primary" @click="submit">确认查询</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {
        getList,
        delData,
        cleanData,
        importData,
        downTemplate,
        downData,
        selectBatchDownload,
        getPercent,
        download,
        illPatientDownload
    } from "@/api/medicalSicknessManage/index";
    import { getToken } from "@/utils/auth";
    export default {
        name: "MedicalSicknessManage/index",
        data() {
            return {
                uploadUrl: process.env.VUE_APP_BASE_API + "/bus/illPatient/importData", // 上传的图片服务器地址
                uploadBatchQuery: process.env.VUE_APP_BASE_API + "/bus/illPatient/batchQueryImportData", //  批量导入
                headers: {
                    Authorization: "Bearer " + getToken(),
                },
                showSearch: true,
                tableKey: 0,
                // 遮罩层
                loading: false,
                // 总条数
                total: 10,
                // 角色表格数据
                roleList: [],
                types: {
                    1: "医保甲类",
                    2: "医保乙类",
                    3: "医保丙类",
                },
                // 查询参数
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    medicineName: "",
                    medicineId: "",
                    placePointName: "",
                    identityCard: "",
                    tel: "",
                    patientName: ""
                },
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                isShow: false,
                fileList: [],
                batchQuery: {}, // 批量查询
            };
        },
        created() {
            this.getListData();

        },

        methods: {
            //编辑
            handleUpdate(row) {
                if (row.hasImage != 1) {
                    return this.$message.error("该患者没有图片，无法编辑！")
                }
                sessionStorage.setItem('updateStorage', 1)
                console.log('查询条件1', this.queryParams)
                sessionStorage.setItem('queryParams', JSON.stringify(this.queryParams))


                this.$router.push(`/editImg?id=${row.id}`)
            },
            handleDwon(row) {

                if (row.hasImage != 1) {
                    return this.$message.error("该患者没有图片，无法下载！")
                }
                downData(row).then(res => {
                    let blob = new Blob([res], { type: 'application/zip' })
                    let url = window.URL.createObjectURL(blob)
                    const link = document.createElement('a') // 创建a标签
                    link.href = url
                    link.download = `${row.medicineName}_${row.name}`   // 重命名文件
                    link.click()
                    URL.revokeObjectURL(url) // 释放内存
                })
            },
            // 删除
            deleteAll() {
                this.$prompt("请输入密码", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    beforeClose: (action, instance, done) => {
                        if (action == "confirm") {
                            if (!instance.inputValue)
                                return this.$message.error("请输入密码！");
                            if (instance.inputValue != "123456")
                                return this.$message.error("密码错误！");
                            cleanData().then(() => {
                                this.$message.success("删除成功！");
                                this.getListData();
                                done();
                            });
                        } else {
                            done();
                        }
                    },
                });
            },
            // 上传前校检格式和大小
            handleBeforeUpload(file) {
                console.log(file);
                const type = [
                    ".xlsx",
                    ".xls",
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                ];
                const isJPG = type.includes(file.type);
                // 检验文件格式
                if (!isJPG) {
                    this.$message.error(`文件格式错误!`);
                    return false;
                }
                return true;
            },
            // 批量查询上传
            handleUploadSuccess(res, file) {
                // 如果上传成功
                if (res.code == 200) {
                    this.batchQuery.identityCardList = res.identityCardList
                    this.batchQuery.patientNameList = res.patientNameList

                } else {
                    this.$message.error("文件上传失败");
                }
            },
            downloadTemplate() {
                this.download("/bus/illPatient/importTemplate", {}, `大病患者管理模板.xlsx`);
            },
            // 批量下载
            bindExport() {
                console.log(this.ids)
                if (this.ids.length < 1) {
                    return this.$message.error("请勾选需要下载的选项！")
                }
                this.loading = true;
                let data = this.ids.toString()
                selectBatchDownload(data).then(res => {
                    console.log('多条数据勾选批量下载', res)
                    if (res.code == 200) {
                        this.downloadKey = res.key
                        this.downloadFileName = res.fileName
                        setTimeout(() => {
                            this.loading = false;
                            this.toGetPercent()
                        }, 3000)
                    } else {
                        this.loading = false;
                        return this.$message.error("获取资源失败！")
                    }
                })
            },
            // 多条数据勾选批量下载进度查看
            toGetPercent() {
                this.loading = true;
                getPercent(this.downloadKey).then(res => {
                    console.log('多条数据勾选批量下载进度查看', res)
                    if (res.code == 200) {
                        if (res.data == 100) {
                            this.loading = false;
                            this.getDownload()
                        } else if (res.data == -1) {
                            this.loading = false;
                            this.$message.error("生成失败，无文件")

                            return
                        }
                        else {
                            setTimeout(() => {
                                this.loading = false;
                                this.toGetPercent()
                            }, 3000)
                        }
                    } else {
                        this.loading = false;
                    }


                })
            },
            // 下载
            getDownload() {

                let data = `?key=${this.downloadKey}&fileName=${this.downloadFileName}`
                download(data).then(res => {

                    if (!res) return
                    const link = document.createElement('a')
                    let blob = new Blob([res], {
                        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                    })
                    link.style.display = 'none'
                    link.href = URL.createObjectURL(blob)
                    link.setAttribute('download', `大病患者信息_${this.format(Date.now())}.zip`)
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link)
                    this.$message({
                        message: '下载成功',
                        type: 'success'
                    });
                    this.downloadKey = ''
                    this.downloadFileName = ''
                })
            },
            format(date) {
                let time = new Date(date)
                const year = time.getFullYear();
                const month = (time.getMonth() + 1).toString().padStart(2, '0');
                const day = time.getDate().toString().padStart(2, '0');
                // 获取小时（0-23）
                const hours = time.getHours().toString().padStart(2, '0');
                // 获取分钟（0-59）
                const minutes = time.getMinutes().toString().padStart(2, '0');
                const formattedDate = `${year}-${month}-${day} ${hours}-${minutes}`;
                return formattedDate
            },

            /** 导出按钮操作 */
            handleExport() {

                this.download(
                    "/bus/illPatient/export",
                    {
                        ...this.queryParams,
                    },
                    `大病患者管理列表_${new Date().getTime()}.xlsx`
                );
            },
            /** 查询角色列表 */
            getListData() {
                this.loading = true;
                getList({ ...this.queryParams }).then((response) => {
                    this.roleList = response.data.records;
                    this.total = response.data.total || 0;
                    this.loading = false;
                });
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.$nextTick(() => {
                    this.getListData();
                });
            },
            /** 重置按钮操作 */
            resetQuery() {
                sessionStorage.removeItem('updateStorage')
                this.queryParams = {
                    pageNum: 1,
                    pageSize: 10,
                    medicineName: "",
                    medicineId: "",
                    placePointName: "",
                    identityCard: "",
                    tel: "",
                    patientName: ""
                }
                this.resetForm("queryForm");
                this.handleQuery();
            },
            /** 添加按钮操作 */
            handleAdd() { },
            selectable(row, index) {
                return row.hasImage == 1 ? true : false;
            },
            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map((item) => item.id);
                this.single = selection.length != 1;
                this.multiple = !selection.length;
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                if (!this.ids.length) {
                    return this.$message.error("请选择要删除的数据");
                }
                const roleIds = this.ids;
                this.$modal
                    .confirm("是否确认删除数据？")
                    .then(function () {
                        return delData(roleIds);
                    })
                    .then(() => {
                        this.getListData();
                        this.$modal.msgSuccess("删除成功");
                    })
                    .catch(() => { });
            },
            // 批量查询
            submit() {
                console.log(this.batchQuery)
                this.queryParams = {
                    pageNum: 1,
                    pageSize: 10,
                    ...this.batchQuery
                }
                this.$nextTick(()=>{
                    this.getListData()
                    this.isShow = false
                })

            },
            handleChange() {

            },
            // 导入模板下载
            downloadTemp() {
                this.download("/bus/illPatient/batchQueryImportTemplate", {}, `批量查询模板.xlsx`);
            },
        },
    };
</script>
<style lang="scss" scoped>
    .footerForm {
        margin-left: 200px;
    }

    .formBox {
        width: 600px;
        margin-top: 40px;
    }

    .btnText {
        color: #0052d9 !important;
    }

    .dialogForm {
        ::v-deep .el-form-item {
            margin-bottom: 10px;
        }

        ::v-deep.el-form--label-top .el-form-item__label {
            padding: 0;
        }
    }

    .add {
        background: #0052d9;
        color: #fff;
        border: none;
    }

    .delBtn {
        background: #e7e7e7;
        color: #000;
        border: none;
        margin-left: 10px;
    }

    .open {
        width: 52px;
        height: 32px;
        background: #e3f9e9;
        border-radius: 3px 3px 3px 3px;
        border: 1px solid #2ba471;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 400;
        font-size: 14px;
        color: #2ba471;
    }

    .close {
        width: 52px;
        height: 32px;
        background: #d8d8d8;
        border-radius: 3px 3px 3px 3px;
        border: 1px solid #767676;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 400;
        font-size: 14px;
        color: #767676;
    }

    .statusBox {
        width: 100%;
        display: flex;
        justify-content: center;
    }

    .status_div {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 66px;
        height: 32px;
        background: #ffffff;
        border-radius: 3px;
        border: 1px solid #e7e7e7;
        font-size: 14px;
        background: #f3f3f3;
        color: rgba(0, 0, 0, 0.9);
        line-height: 1;

        &.jxz {
            background: #f2f3ff;
            border: 1px solid #0052d9;
            color: #0052d9;
        }

        &.ywc {
            background: #e3f9e9;
            border: 1px solid #2ba471;
            color: #2ba471;
        }
    }

    .img {
        width: 38px;
        height: 38px;
    }

    .flex_box {
        display: flex;
    }

    .btnBox {
        display: flex;
        align-items: flex-start;
    }
</style>